using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.ObjectBuilder;
using System.Windows;
using Microsoft.Practices.CompositeUI;

namespace Jbe.CABExtension.WPF
{
    /// <summary>
    /// A <see cref="BuilderStrategy"/> that hooks up a <see cref="UIElement"/> with the 
    /// <see cref="IUIElementActivationService"/>.
    /// </summary>
    public class UIElementActivationStrategy : BuilderStrategy
    {
        /// <summary>
        /// Hooks the element if it is a <see cref="UIElement"/>.
        /// </summary>
        public override object BuildUp(IBuilderContext context, Type t, object existing, string id)
        {
            UIElement uiElement = existing as UIElement;

            if (uiElement != null)
            {
                WorkItem wi = context.Locator.Get<WorkItem>(new DependencyResolutionLocatorKey(typeof(WorkItem), null));
                wi.Services.Get<IUIElementActivationService>(true).UIElementAdded(uiElement);
            }

            return base.BuildUp(context, t, existing, id);
        }

        /// <summary>
        /// Notifies the <see cref="IUIElementActivationService"/> to remove the <see cref="UIElement"/>.
        /// </summary>
        public override object TearDown(IBuilderContext context, object item)
        {
            UIElement uiElement = item as UIElement;
            if (uiElement != null)
            {
                WorkItem wi = context.Locator.Get<WorkItem>(new DependencyResolutionLocatorKey(typeof(WorkItem), null));
                wi.Services.Get<IUIElementActivationService>(true).UIElementRemoved(uiElement);

            }
            return base.TearDown(context, item);
        }
    }
}
